package com.scaffold.myproject.service.impl.item;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scaffold.myproject.common.PageResult;
import com.scaffold.myproject.entity.item.ItemDoc;
import com.scaffold.myproject.model.req.item.ItemPageReq;
import com.scaffold.myproject.service.item.ItemService;
import com.scaffold.myproject.mapper.item.ItemMapper;
import com.scaffold.myproject.entity.item.ItemEntity;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scaffold.myproject.utils.EsPageQueryUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 商品表 数据实现类
 * </p>
 *
 * @author LX
 * @since 2025-10-29
 */
@Slf4j
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, ItemEntity> implements ItemService {
    @Resource
    private ItemMapper itemMapper;
    @Resource
    private EsPageQueryUtil esPageQueryUtil;

    @Override
    public PageResult<ItemEntity> searchPageFromDb(ItemPageReq req) {
        LambdaQueryWrapper<ItemEntity> queryWrapper = new LambdaQueryWrapper<>();

    // 模糊匹配 name 和 category
        if (req.getName() != null && !req.getName().isBlank()) {
            queryWrapper.like(ItemEntity::getName, req.getName());
        }
        if (req.getCategory() != null && !req.getCategory().isBlank()) {
            queryWrapper.like(ItemEntity::getCategory, req.getCategory());
        }

        // 2. 品牌过滤
        if (req.getBrand() != null && !req.getBrand().isBlank()) {
            queryWrapper.eq(ItemEntity::getBrand, req.getBrand());
        }

        // 3. 价格区间过滤
        if (req.getMinPrice() != null) {
            queryWrapper.ge(ItemEntity::getPrice, req.getMinPrice());
        }
        if (req.getMaxPrice() != null) {
            queryWrapper.le(ItemEntity::getPrice, req.getMaxPrice());
        }

        // 4. 动态排序（支持：price / sold / createTime）
        String sortField = req.getSortField();
        boolean asc = "asc".equalsIgnoreCase(req.getSortOrder());

        if ("sold".equalsIgnoreCase(sortField)) {
            if (asc) {
                queryWrapper.orderByAsc(ItemEntity::getSold);
            } else {
                queryWrapper.orderByDesc(ItemEntity::getSold);
            }
        } else if ("createTime".equalsIgnoreCase(sortField)) {
            if (asc) {
                queryWrapper.orderByAsc(ItemEntity::getCreateTime);
            } else {
                queryWrapper.orderByDesc(ItemEntity::getCreateTime);
            }
        } else { // 默认 price
            if (asc) {
                queryWrapper.orderByAsc(ItemEntity::getPrice);
            } else {
                queryWrapper.orderByDesc(ItemEntity::getPrice);
            }
        }

        // 5. 分页查询
        Page<ItemEntity> page = new Page<>(req.getPageNo(), req.getPageSize());
        Page<ItemEntity> resultPage = itemMapper.selectPage(page, queryWrapper);

        // 6. 封装返回结果
        return new PageResult<>(
                resultPage.getRecords(),
                (int) resultPage.getTotal(),
                (int) resultPage.getSize(),
                (int) resultPage.getCurrent()
        );
    }

    @Override
    public PageResult<ItemDoc> searchPage(ItemPageReq req) throws IOException {
        // 1. 创建 bool 查询
        BoolQueryBuilder bool = QueryBuilders.boolQuery();

        // === (1) 关键字搜索 ===
        if (req.getName() != null && !req.getName().isBlank()) {
            bool.must(QueryBuilders.matchQuery("name", req.getName()));
        }
        if (req.getCategory() != null && !req.getCategory().isBlank()) {
            bool.must(QueryBuilders.matchQuery("category", req.getCategory()));
        }

        // === (2) 品牌过滤 ===
        if (req.getBrand() != null && !req.getBrand().isBlank()) {
            bool.filter(QueryBuilders.termQuery("brand", req.getBrand()));
        }

        // === (3) 价格范围过滤 ===
        if (req.getMinPrice() != null || req.getMaxPrice() != null) {
            var range = QueryBuilders.rangeQuery("price");
            if (req.getMinPrice() != null) range.gte(req.getMinPrice());
            if (req.getMaxPrice() != null) range.lte(req.getMaxPrice());
            bool.filter(range);
        }

        // 2. 调用通用分页工具执行查询
        return esPageQueryUtil.searchPage(
                "items",
                bool,
                req.getPageNo(),
                req.getPageSize(),
                req.getSortField(),
                req.getSortOrder(),
                ItemDoc.class
        );
    }
}